package com.futvan.z.framework.core;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyClientCloseListener extends ChannelInboundHandlerAdapter {
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        z.Log("连接关闭|channelId:"+ctx.channel().id());
        ClearUserChannel(String.valueOf(ctx.channel().id()));
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
        z.Log("连接异常关闭|channelId:"+ctx.channel().id()+"|Throwable:"+e.getMessage());
        ClearUserChannel(String.valueOf(ctx.channel().id()));
        ctx.close();
    }

    /**
     * 清理Channel信息
     * @param channelid
     */
    private void ClearUserChannel(String channelid){
        z.getSqlSession().delete("delete","delete from z_user_channels where channelid = '"+channelid+"'");
        if(NettyWebSocketHandler.channels.containsKey(channelid)){
            NettyWebSocketHandler.channels.remove(channelid);
        }
    }
}
